package com.haierp.controller.purchase;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.haierp.enums.GeneralStatus;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.PurchaseStorageDetailMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.ItemSku;
import com.haierp.model.Warehouse;
import com.haierp.model.purchase.PurchaseStorage;
import com.haierp.model.purchase.PurchaseStorageDetail;
import com.haierp.service.*;
import com.haierp.service.purchase.IPurchaseStorageService;
import com.haierp.util.DateUtil;
import com.haierp.util.ExcelTool.ExcelHelper;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.NumberUtil;
import com.haierp.vo.PurchaseStorageVO;
import com.haierp.vo.json.PicModel;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.User;
import com.wangzhixuan.service.IUserService;
import org.apache.commons.collections.CollectionUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.*;


@Controller
@RequestMapping("/purchaseStorage")
public class PurchaseStorageController extends BaseController  {
	@Autowired
	private IWarehouseService warehouseService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	@Autowired
	private IPurchaseStorageService purchaseStorageService;
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IItemSkuService itemSkuService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	IErpOrderService erpOrderService;
	
	@Autowired
	private PurchaseStorageDetailMapper purchaseStorageDetailMapper;
	
	/**
	 *新增入库单
	 * @param
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object add(PurchaseStorage purchaseStorage,String purchaseStorageDetails) {
		ShiroUser shiroUser = this.getShiroUser();
		purchaseStorage.setCompanyId(shiroUser.getCompanyId());//s所属公司
		JsonResult<String> result = new JsonResult<>();
		try{
			initAddPurchaseStorage(purchaseStorage,purchaseStorageDetails);
		}catch(ErpCommonException e){
			return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
		}catch(Exception ex){
			logger.error(ex);
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
		purchaseStorageService.addPurchaseStorage(purchaseStorage);
	    return	result.buildIsSuccess(true);
	}

	/**
	 * 新增入库单初始化
	 * @param purchaseStorage
	 * @param purchaseStorageDetails
	 */
	private void initAddPurchaseStorage(PurchaseStorage purchaseStorage,String purchaseStorageDetails){
		ShiroUser shiroUser = this.getShiroUser();
		purchaseStorage.setCompanyId(shiroUser.getCompanyId());//s所属公司
		purchaseStorage.setGmtCreate(new Date());
		purchaseStorage.setGmtModify(new Date());
		purchaseStorage.setStatus(GeneralStatus.INIT.getCode());
		//数据校验
		List<PurchaseStorageDetail> psdList=null;
		psdList = validatePurchaseStorage(purchaseStorage,purchaseStorageDetails);
		purchaseStorage.setStoOrderNo("G"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+"U"+String.format("%0"+4+"d", purchaseStorage.getBuyerId())+sequenceUtilService.gainPOSequence());
		User user= userService.selectById(purchaseStorage.getBuyerId());
		if(user!=null){
			purchaseStorage.setBuyerName(user.getName());
		}else{
			throw new ErpCommonException("买手信息有误");
		}
		purchaseStorage.setUserCreate(shiroUser.getName());
		purchaseStorage.setPurchaseStorageDetailList(psdList);
		
	}
	
	/**
	 * 对用户的入库单数据校验，失败thow exception
	 * @param purchaseStorage
	 */
	private  List<PurchaseStorageDetail>  validatePurchaseStorage(PurchaseStorage purchaseStorage,String purchaseStorageDetails) {
		//校验仓库
		if(purchaseStorage.getWarehouseId()!=null){
			Long wareid = purchaseStorage.getWarehouseId();
			Warehouse house = warehouseService.selectById(wareid);
			if(house==null){
				throw new ErpCommonException("没有找到仓库ID:"+wareid);
			}
			purchaseStorage.setWarehouseName(house.getName());
			
		}else{
			throw new ErpCommonException("没有仓库ID");
		}
		
		//TODO 买手信息校验
		List<PurchaseStorageDetail> psdList = null;
		//校验详细
		if (StringUtils.isNotBlank(purchaseStorageDetails)) {
			String s  = purchaseStorageDetails.replace("&quot;", "\"");
			psdList = HaiJsonUtils.toBean(s, new TypeReference<List<PurchaseStorageDetail>>(){});
			Integer totalQuantity = 0;
			Integer totalTransQuantity = 0;
			Double totalQuantityPrice = 0.0d;
			Double totalTransQuantityPrice = 0.0d;
			Double totalTaxPrice = 0.0d;
			for(PurchaseStorageDetail psd:psdList){
				if(psd.getPrice()==null||psd.getPrice()<=0.0d){
					throw new ErpCommonException("商品价格有误，SKUCODE:"+psd.getSkuCode());
				}
				if(psd.getQuantity()+psd.getTransQuantity()==0){
					throw new ErpCommonException("商品数量有误，SKUCODE:"+psd.getSkuCode());
				}
				double totalPrice = 0.0d;
				if(psd.getPrice()!=null && psd.getPrice()>0) {
					totalQuantityPrice += psd.getPrice() * psd.getQuantity();
					totalTransQuantityPrice += psd.getPrice() * psd.getTransQuantity();
					totalPrice = psd.getPrice() * psd.getQuantity() + psd.getPrice() * psd.getTransQuantity();
				}
				if(psd.getPurchasePrice() != null && psd.getPurchasePrice() > 0) {
					totalTaxPrice += psd.getPurchasePrice() * psd.getQuantity() + psd.getPurchasePrice() * psd.getTransQuantity();
				}
				psd.setTotalPrice(NumberUtil.formatDoubleTwo(totalPrice));
				totalQuantity += psd.getQuantity();
				totalTransQuantity += psd.getTransQuantity();
				if(StringUtils.isBlank(psd.getShelfNo())){
					throw new ErpCommonException("商品未填货架号"+psd.getSkuId());
				}
				psd.setOnlineNumber(purchaseStorage.getOnlineNumber());
				
				if(purchaseStorage.isIfConfirm() && purchaseStorage.getCompanyId() == 1L && purchaseStorage.getWarehouseId() != 3L) {
					if(psd.getTransQuantity() > 0 && StringUtils.isBlank(purchaseStorage.getOnlineNumber())){
						throw new ErpCommonException("在途SKU请填写网购单号"+psd.getSkuCode());
					}
					psd.setOnlineQuantity(psd.getTransQuantity());
				}
			}
			if(purchaseStorage.isIfConfirm()) {
				purchaseStorage.setTotalQuantity(totalQuantity);
				purchaseStorage.setTotalTransQuantity(totalTransQuantity);
				purchaseStorage.setTotalPrice(NumberUtil.formatDoubleTwo(totalQuantityPrice+totalTransQuantityPrice));
				if(purchaseStorage.getTaxRate() == null || purchaseStorage.getTaxRate() == 0) {
					purchaseStorage.setTotalTaxPrice(totalTaxPrice);
				}
			}
		} else {
			throw new ErpCommonException("商品数量有误"); 
		}
		
		//初始化商品信息
		if(CollectionUtils.isNotEmpty(psdList)){
			Map<Long,ItemSku> skuMap = Maps.newHashMap();
			List<ItemSku> needUpdateUpcList = new ArrayList<ItemSku>();
			for(PurchaseStorageDetail detail:psdList){
				ItemSku itemSku = null;
				if(skuMap.containsKey(detail.getSkuId())){
					 itemSku = skuMap.get(detail.getSkuId());
				}else{
					itemSku = itemSkuService.selectById(detail.getSkuId());
					skuMap.put(detail.getSkuId(), itemSku);
				}
				if(itemSku==null){
					throw new ErpCommonException("商品信息有误"+detail.getSkuId());
				}
				detail.setItemId(itemSku.getItemId());
				detail.setSkuCode(itemSku.getSkuCode());
				if(StringUtil.isNotBlank(detail.getUpc()) && !detail.getUpc().equals(itemSku.getUpc())) {	//修改upc
					itemSku.setUpc(detail.getUpc());
					needUpdateUpcList.add(itemSku);
					
					//订正订单明细里面的upc数据
					ErpOrder erpOrder = new ErpOrder();
					erpOrder.setSkuId(detail.getSkuId());
					erpOrder.setUpc(detail.getUpc());
					erpOrderService.updateUpcForOrder(erpOrder);
				} else {
					detail.setUpc(itemSku.getUpc());
				}
			}
			if(needUpdateUpcList.size()>0) {
				itemSkuService.updateBatchById(needUpdateUpcList);
			}
		}
		return psdList;
	}
	
	/**
	 *更新入库单
	 * @param
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Object update(PurchaseStorage purchaseStorage,String purchaseStorageDetails) {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		purchaseStorage.setCompanyId(one.getCompanyId());//修改入库单加入companyId
		if(purchaseStorage.getId()==null){
			return result.buildIsSuccess(false).buildMsg("没有ID");
		}else{
			PurchaseStorage purSto = purchaseStorageService.selectById(purchaseStorage.getId());
			if(purSto==null||purSto.getStatus()!=GeneralStatus.INIT.getCode()){
				return result.buildIsSuccess(false).buildMsg("状态不对");
			}
		}
		purchaseStorage.setGmtModify(new Date());
		//数据校验
		List<PurchaseStorageDetail> psdList=null;
		try{
			psdList = validatePurchaseStorage(purchaseStorage,purchaseStorageDetails);
		}catch(ErpCommonException e){
			return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
		}catch(Exception ex){
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
		purchaseStorage.setPurchaseStorageDetailList(psdList);
		purchaseStorageService.updatePurchaseStorage(purchaseStorage);
		return	result.buildIsSuccess(true);
	}

	
	/**
	 * 确认入库,区分新增入库和修改入库，逻辑不同
	 * @param
	 * @return
	 */
	@RequestMapping("/confirm")
	@ResponseBody
	public Object confirm(PurchaseStorage purchaseStorage,String purchaseStorageDetails) {
		ShiroUser shiroUser = this.getShiroUser();
		purchaseStorage.setCompanyId(shiroUser.getCompanyId());//s所属公司
		JsonResult<String> result = new JsonResult<>();
		if(purchaseStorage.getId()==null){//新增入库
			//新增
			try {
		    purchaseStorage.setIfConfirm(true);	//直接扫描入库
			initAddPurchaseStorage(purchaseStorage,purchaseStorageDetails);
			} catch (ErpCommonException e) {
				return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
			}catch(Exception ex){
				return result.buildIsSuccess(false).buildMsg("未知异常");
			}
			purchaseStorage.setStatus(GeneralStatus.CONFIRM.getCode());
			purchaseStorage.setPutInDate(new Date());
			purchaseStorageService.addConfirmPurchaseStorage(purchaseStorage);
			increaseInventory(purchaseStorage);
			//确认入库
			return result.buildIsSuccess(true);
			
		}else{//修改入库
			PurchaseStorage purSto = purchaseStorageService.selectById(purchaseStorage.getId());
			if (purSto == null || purSto.getStatus() != GeneralStatus.INIT.getCode()) {
				return result.buildIsSuccess(false).buildMsg("状态不对");
			}
			purchaseStorage.setStatus(GeneralStatus.CONFIRM.getCode());
			purchaseStorage.setUserModify(shiroUser.getLoginName());
			purchaseStorage.setGmtModify(new Date());
			purchaseStorage.setPutInDate(new Date());
			// 数据校验
			List<PurchaseStorageDetail> psdList = null;
			try {
				purchaseStorage.setIfConfirm(true);	//直接扫描入库
				psdList = validatePurchaseStorage(purchaseStorage, purchaseStorageDetails);
			} catch (ErpCommonException e) {
				return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
			}catch(Exception ex){
				ex.printStackTrace();
				return result.buildIsSuccess(false).buildMsg("未知异常");
			}
			if (CollectionUtils.isEmpty(psdList)) {
				return result.buildIsSuccess(false).buildMsg("没有入库单明细");
			}
			purchaseStorage.setPurchaseStorageDetailList(psdList);
			purchaseStorageService.confirmPurchaseStorage(purchaseStorage);
			increaseInventory(purchaseStorage);
		}
		return	result.buildIsSuccess(true);
	}
	
	private void increaseInventory(PurchaseStorage ps) {
		if(CollectionUtils.isNotEmpty(ps.getPurchaseStorageDetailList())){
			Set<Long> skuIds = Sets.newHashSet();
			for(PurchaseStorageDetail psd:ps.getPurchaseStorageDetailList()){
				skuIds.add(psd.getSkuId());
			}
			for(Long skuId:skuIds){
				try {
					//入库时释放在途备货的子订单
					List<ErpOrder> erpOrders = erpOrderService.queryTransStockUpErpOrders(skuId);
					if(erpOrders!=null && erpOrders.size()>0) {
						for (ErpOrder erpOrder : erpOrders) {
							inventoryService.releaseInventory(erpOrder);
						}
					}
					erpOrderService.lockErpOrderBySkuId(skuId);
				} catch (InventoryException e) {
					logger.info("入库锁库存异常skuid:"+skuId, e);
				}
			}
		}
	}
	
	/**
	 *查询单个入库单(拦截器硬编码)
	 * @param
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Object query(Long id) {
		ShiroUser one = this.getShiroUser();
		JsonResult<PurchaseStorage> result = new JsonResult<>();
		if(id==null){
			return result.buildIsSuccess(false).buildMsg("没有ID");
		}else{
			PurchaseStorage purchaseStorage = purchaseStorageService.queryPurchaseStorage(id,one.getCompanyId());
			return result.buildData(purchaseStorage).buildIsSuccess(true);
		}
	}

	/**
	 *批量查询入库单
	 * @param
	 * @return
	 */
	@RequestMapping("/queryPurStorages")
	@ResponseBody
	public Object queryPurStorages(PurchaseStorageVO psVO) {
		//如果是第三方买手
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		if(roles.contains("irhbuyer")) {
			psVO.setBuyerId(shiroUser.getId());
		}
		JsonPageResult<List<PurchaseStorage>> result = purchaseStorageService.queryPurStorages(psVO);
		if(roles.contains("irhbuyer") && !roles.contains("cgpm_outer")) {
			result.setAgentRoler(true);
		}
		if(roles.contains("noexport")) {
			result.setNoEexportRoler(true);
		}
		return result;
	}
	
	/**
	 *批量入库
	 * @param
	 * @return
	 */
	@RequestMapping("/multiConfirm")
	@ResponseBody
	public Object multiConfirm(String ids) {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		List<String> errorMsgs = Lists.newArrayList();
//		String errorMsg = null;
		if(StringUtils.isNotBlank(ids)){
			 List<Long> a =  HaiJsonUtils.toBean(ids, new TypeReference<List<Long>>(){});
			if(!CollectionUtils.isEmpty(a)){
				for(Long id:a){
					PurchaseStorage purchaseStorage = purchaseStorageService.queryPurchaseStorage(id,one.getCompanyId());
					if(purchaseStorage!=null){
						String errorMsg = multiConfirmValidate(purchaseStorage);
						if(errorMsg!=null){
							errorMsgs.add(errorMsg);
							continue;
						}
					}else{
						errorMsgs.add("id:"+purchaseStorage.getId()+"入库单不存在。");
						continue;
					}
					purchaseStorage.setStatus(GeneralStatus.CONFIRM.getCode());
					purchaseStorage.setGmtModify(new Date());
					purchaseStorage.setPutInDate(new Date());
					try{
						purchaseStorageService.confirmPurchaseStorage(purchaseStorage);
						increaseInventory(purchaseStorage);
					}catch(Exception e){
						e.printStackTrace();
						errorMsgs.add("单号:"+purchaseStorage.getStoOrderNo()+"入库失败");
					}
				}
			}
		}else{
			result.buildIsSuccess(false).buildMsg("数据有误");
		}
		if(CollectionUtils.isNotEmpty(errorMsgs)){
			result.buildIsSuccess(false);
			String rMsg = "";
			for(String m:errorMsgs){
				rMsg+=m;
			}
			result.setMsg(rMsg);
			
		}else{
			result.buildIsSuccess(true);
		}
		
		return result;
		
	}

	private String multiConfirmValidate(PurchaseStorage purchaseStorage) {
		
		if(purchaseStorage.getWarehouseId()!=null){
			Long wareid = purchaseStorage.getWarehouseId();
			Warehouse house = warehouseService.selectById(wareid);
			if(house==null){
				return "单号:"+purchaseStorage.getStoOrderNo()+"仓库信息错误";
			}
			
		}else{
			return "单号:"+purchaseStorage.getStoOrderNo()+"没有仓库信息";
		}
		
		if (purchaseStorage.getStatus() != GeneralStatus.INIT.getCode()) {
			return "单号:"+purchaseStorage.getStoOrderNo()+"不可入库的订单状态";
		}
		List<PurchaseStorageDetail> psdList=purchaseStorage.getPurchaseStorageDetailList();
		if(CollectionUtils.isEmpty(psdList)){
			return "单号:"+purchaseStorage.getStoOrderNo()+"没有入库单明细";
		}
		for(PurchaseStorageDetail psd:psdList){
			if(psd.getPrice()==null||psd.getPrice()<=0.0d){
				return "单号:"+purchaseStorage.getStoOrderNo()+"商品价格有误，SKUCODE:"+psd.getSkuCode();
			}
			if(psd.getQuantity()+psd.getTransQuantity()==0){
				return "单号:"+purchaseStorage.getStoOrderNo()+"没有商品数量，SKUCODE:"+psd.getSkuCode();
			}
			
			if(StringUtils.isBlank(psd.getShelfNo())){
				return "单号:"+purchaseStorage.getStoOrderNo()+"商品未填货架号，SKUCODE"+psd.getSkuCode();
			}
			
		}
		return null;
	}
	
	
	/**
	 *删除入库单
	 * @param
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(Long id) {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		//1、查询
		PurchaseStorage purchaseStorage = purchaseStorageService.queryPurchaseStorage(id,one.getCompanyId());
		if(purchaseStorage!=null){
			//2、判断入库单状态
			if(purchaseStorage.getStatus()!=GeneralStatus.INIT.getCode()){
				result.buildIsSuccess(false).buildMsg("入库单状态错误");
			}else{
				purchaseStorageService.deletePurchaseStorage(purchaseStorage);
				result.buildIsSuccess(true);
			}
			
		}else{
			result.buildIsSuccess(false).buildMsg("没有找到入库单");
		}
		return result;
	}
	
	/**
	 * 根据入库单ID导出excel
	 * @param id
	 */
	@RequestMapping("/purchaseExport")
    public ResponseEntity<byte[]> taskDailyExport(Long id) throws Exception {
		List<Long> storageIdList = Lists.newArrayList();
		List<List<Object>> rowDatas = new ArrayList<>();
    	ShiroUser one = this.getShiroUser();
    	PurchaseStorage purchaseStorage = purchaseStorageService.queryPurchaseStorage(id,one.getCompanyId());
		String mergeIds = purchaseStorage.getMergeIds();
		if(StringUtils.isNotBlank(mergeIds)) {
			storageIdList = HaiJsonUtils.toBean(mergeIds, new TypeReference<List<Long>>() {});
		} else {
			storageIdList.add(id);
		}
		int listLength = storageIdList.size();
		for(int i=0; i<listLength; i++) {
			if(listLength > 1) {
				purchaseStorage = purchaseStorageService.queryPurchaseStorage(storageIdList.get(i), one.getCompanyId());
			}
			List<PurchaseStorageDetail> purchaseStorageDetailList = purchaseStorage.getPurchaseStorageDetailList();
			if(purchaseStorageDetailList != null) {
				for (PurchaseStorageDetail purchaseStorageDetail : purchaseStorageDetailList) {
					List<Object> list = new ArrayList<>();
					//sku图片
					String skuPic = purchaseStorageDetail.getSkuPic();
					if(StringUtil.isNotBlank(skuPic)) {
						PicModel pm = HaiJsonUtils.toBean(skuPic, PicModel.class);
						String imgSrc = pm.getPicList().get(0).getUrl();
						String imgType = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
						if(imgSrc.contains("aliyuncs.com")) {
							imgSrc += "?x-oss-process=image/resize,m_lfit,h_100,w_100";
						} else {
							imgSrc = imgSrc.replaceAll("Resource", "Thumbnail");
						}
						//System.out.println(imgSrc);
						URL url = new URL(imgSrc);
						BufferedImage image = ImageIO.read(url);
						ByteArrayOutputStream output = new ByteArrayOutputStream();
						ImageIO.write(image, imgType, output);
						output.flush();
						list.add(output.toByteArray());
						output.close();
					} else {
						list.add(null);
					}
					list.add(purchaseStorageDetail.getSkuCode());			//SKU代码
					list.add(purchaseStorageDetail.getItemName());			//商品名称
					list.add(purchaseStorageDetail.getUpc());				//UPC
					list.add(purchaseStorageDetail.getColor());				//颜色
					list.add(purchaseStorageDetail.getScale());				//尺码
					list.add(purchaseStorageDetail.getBuySite());           //采购站点
					list.add(purchaseStorageDetail.getTaskDailyCount());	//计划采购数
					list.add(purchaseStorageDetail.getQuantity());			//现货入库数
					list.add(purchaseStorageDetail.getTransQuantity());		//在途入库数
					//未入库数
					if(purchaseStorageDetail.getTaskDailyCount() != null) {
						list.add(purchaseStorageDetail.getTaskDailyCount() - purchaseStorageDetail.getQuantity() - purchaseStorageDetail.getTransQuantity());
					} else {
						list.add(null);
					}
					list.add(purchaseStorageDetail.getPrice());				//单价
					list.add(purchaseStorageDetail.getTotalPrice());		//总价
					list.add(purchaseStorageDetail.getWarehouseName());		//仓库
					list.add(purchaseStorageDetail.getShelfNo());			//货架号
					list.add(null);											//税率
					list.add(null);											//合计

					rowDatas.add(list);
				}
			}

			List<Object> list = new ArrayList<>();
			list.add(null);	//图片
			list.add(null);	//SKU代码
			list.add(null);	//商品名称
			list.add(null);	//UPC
			list.add(null);	//颜色
			list.add(null);	//尺码
			list.add(null);	//采购站点
			list.add(null);	//计划采购数
			list.add(null);	//现货入库数
			list.add(null);	//在途入库数
			list.add(null);	//未入库数
			list.add(null);	//单价
			list.add(purchaseStorage.getTotalPrice());		//总价
			list.add(null);	//仓库
			list.add(null);	//货架号
			//税率
			if(purchaseStorage.getTaxRate() != null) {
				list.add(purchaseStorage.getTaxRate() + "%");
			} else {
				list.add(null);
			}
			list.add(purchaseStorage.getTotalTaxPrice());	//合计
			rowDatas.add(list);
		}

    	ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"商品图片", "SKU代码", "商品名称", "UPC", "颜色", "尺码", "采购站点", "计划采购数", "现货入库数", "在途入库数", "未入库数", "单价", "总价", "仓库", "货架号", "税率", "合计"};
    	Integer[] columnWidth = new Integer[]{15, 25, 30, 25, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15};
    	excelHelper.setPurchaseStorageToSheet("Erp Order", columnTitles, rowDatas, columnWidth);
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "入库单(" + DateUtil.formatDate(purchaseStorage.getGmtCreate(), "yyyyMMdd") + ").xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
    	return filebyte;
    }
    
    @RequestMapping("/mergePurchaseStorage")
	@ResponseBody
	public Object mergePurchaseStorage(String ids) {
    	JsonResult<String> result = new JsonResult<String>();
    	ShiroUser one = this.getShiroUser();
    	result = purchaseStorageService.mergePurchaseStorage(ids,one.getCompanyId());
    	return result;
    }
    /**
     * 拆分入库单
     * @param purchaseStorage
     * @param purchaseStorageDetails
     * @return
     */
    @RequestMapping("/splitStorage")
	@ResponseBody
	public Object splitStorage(PurchaseStorage purchaseStorage,String purchaseStorageDetails) {
		ShiroUser shiroUser = this.getShiroUser();
		purchaseStorage.setCompanyId(shiroUser.getCompanyId());//s所属公司
		PurchaseStorage  newSpiltone = purchaseStorageService.selectById(purchaseStorage.getId());
		newSpiltone.setLinebuyerId(purchaseStorage.getBuyerId());
		newSpiltone.setOnlineNumber(purchaseStorage.getOnlineNumber());
		newSpiltone.setLinewarehouseId(purchaseStorage.getWarehouseId());
		User user= userService.selectById(purchaseStorage.getBuyerId());
		if(user!=null){
			newSpiltone.setLinebuyerName(user.getName());
		}else{
			throw new ErpCommonException("买手信息有误");
		}
		//数据校验
		List<PurchaseStorageDetail> psdList=null;
		JsonResult<String> result = new JsonResult<>();
		try{
			psdList = validateSpiltPurchaseStorage(newSpiltone,purchaseStorageDetails);
		}catch(ErpCommonException e){
			return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
		}catch(Exception ex){
			logger.error(ex);
			return result.buildIsSuccess(false).buildMsg("未异常");
		}
		purchaseStorageService.updateSelectiveById(newSpiltone);
		for (PurchaseStorageDetail purchaseStorageDetail : psdList) {
			purchaseStorageDetailMapper.updateById(purchaseStorageDetail);
		}
		//删除拆分之后在途0 数量0
        for (PurchaseStorageDetail purchaseStorageDetail : psdList) {
      	  if (purchaseStorageDetail.getQuantity() == 0 && purchaseStorageDetail.getTransQuantity() == 0) {
      		  purchaseStorageDetailMapper.deleteSelective(purchaseStorageDetail);
      	  }
		}
	    return	result.buildIsSuccess(true);
	}
    
	/**
	 * 对用户的入库单数据校验，失败thow exception
	 * @param purchaseStorage
	 */
	private  List<PurchaseStorageDetail>  validateSpiltPurchaseStorage(PurchaseStorage purchaseStorage,String purchaseStorageDetails) {
		List<PurchaseStorageDetail> psdList = null;
		List<PurchaseStorageDetail> spiltNewDetail = new ArrayList<PurchaseStorageDetail>();
		List<PurchaseStorageDetail> spiltOldDetail = new ArrayList<PurchaseStorageDetail>();
		//校验详细
		if (StringUtils.isNotBlank(purchaseStorageDetails)) {
			String s  = purchaseStorageDetails.replace("&quot;", "\"");
			psdList = HaiJsonUtils.toBean(s, new TypeReference<List<PurchaseStorageDetail>>(){});
			for(PurchaseStorageDetail psd:psdList){
				PurchaseStorageDetail one = purchaseStorageDetailMapper.selectById(psd.getId());
				one.setSpiltNumber(psd.getSpiltNumber());
				spiltOldDetail.add(one);
			}
		} else {
			throw new ErpCommonException("商品数量有误"); 
		}
			//写入更改后的detail
			if(spiltOldDetail.size() > 0) {
				Integer totalQuantity = 0;
				Integer totalTransQuantity = 0;
				Double totalQuantityPrice = 0.0d;
				Double totalTransQuantityPrice = 0.0d;
				for (PurchaseStorageDetail purchaseStorageDetail : spiltOldDetail) {
					if(purchaseStorageDetail.getSpiltNumber()>0){
						if(purchaseStorageDetail.getSpiltNumber() > purchaseStorageDetail.getTransQuantity()) {
							throw new ErpCommonException("所填拆分在途数量有误，SKUCODE:"+purchaseStorageDetail.getSkuCode());
						} else {
							purchaseStorageDetail.setTransQuantity(purchaseStorageDetail.getTransQuantity() - purchaseStorageDetail.getSpiltNumber());
							PurchaseStorageDetail purchaseStorageDetailNew = new PurchaseStorageDetail();
							BeanUtils.copyProperties(purchaseStorageDetail, purchaseStorageDetailNew);
							purchaseStorageDetailNew.setId(null);
							purchaseStorageDetailNew.setGmtCreate(new Date());
							purchaseStorageDetailNew.setGmtModify(new Date());
							purchaseStorageDetailNew.setUserCreate("自动拆分");
							purchaseStorageDetailNew.setTransQuantity(purchaseStorageDetail.getSpiltNumber());
							purchaseStorageDetailNew.setStorageId(null);
							purchaseStorageDetailNew.setStoOrderNo(null);
							purchaseStorageDetailNew.setQuantity(0);
							purchaseStorageDetailNew.setTotalPrice(purchaseStorageDetailNew.getTransQuantity() * purchaseStorageDetailNew.getPrice());
							purchaseStorageDetailNew.setOnlineQuantity(purchaseStorageDetail.getSpiltNumber());//网购实际数量，在途入库增使用
							spiltNewDetail.add(purchaseStorageDetailNew);
						}
				}
					double totalPrice = 0.0d;
					if(purchaseStorageDetail.getPrice()!=null && purchaseStorageDetail.getPrice()>0) {
						totalQuantityPrice += purchaseStorageDetail.getPrice() * purchaseStorageDetail.getQuantity();
						totalTransQuantityPrice += purchaseStorageDetail.getPrice() * purchaseStorageDetail.getTransQuantity();
						totalPrice = purchaseStorageDetail.getPrice() * purchaseStorageDetail.getQuantity() + purchaseStorageDetail.getPrice() * purchaseStorageDetail.getTransQuantity();
					}
					purchaseStorageDetail.setTotalPrice(NumberUtil.formatDoubleTwo(totalPrice));
					totalQuantity += purchaseStorageDetail.getQuantity();
					totalTransQuantity += purchaseStorageDetail.getTransQuantity();
					if(StringUtils.isBlank(purchaseStorageDetail.getShelfNo())){
						throw new ErpCommonException("商品未填货架号"+purchaseStorageDetail.getSkuId());
					}
			}
			
			
			if(purchaseStorage.isIfConfirm()) {
				purchaseStorage.setTotalQuantity(totalQuantity);
				purchaseStorage.setTotalTransQuantity(totalTransQuantity);
				purchaseStorage.setTotalPrice(NumberUtil.formatDoubleTwo(totalQuantityPrice+totalTransQuantityPrice));
			}
			if (spiltNewDetail.size() > 0) {
				PurchaseStorage purchaseStorageNew = new PurchaseStorage();
				BeanUtils.copyProperties(purchaseStorage, purchaseStorageNew);
				purchaseStorageNew.setId(null);
				purchaseStorageNew.setGmtCreate(new Date());
				purchaseStorageNew.setGmtModify(new Date());
				purchaseStorageNew.setTotalQuantity(0);
				purchaseStorageNew.setTotalTransQuantity(0);
				purchaseStorageNew.setTotalPrice(0.0);
				purchaseStorageNew.setStatus(0); //强制不能直接入库
				purchaseStorageNew.setBuyerId(purchaseStorage.getLinebuyerId());
				purchaseStorageNew.setBuyerName(purchaseStorage.getLinebuyerName());
				// 校验仓库
				if (purchaseStorage.getLinewarehouseId() != null) {
					Warehouse house = warehouseService.selectById(purchaseStorage.getLinewarehouseId());
					if (house == null) {
						throw new ErpCommonException("没有找到仓库ID:" + purchaseStorage.getLinewarehouseId());
					}
					purchaseStorageNew.setWarehouseId(purchaseStorage.getLinewarehouseId());
					purchaseStorageNew.setWarehouseName(house.getName());
				} else {
					throw new ErpCommonException("没有仓库ID");
				}
				purchaseStorageNew.setUserCreate("系统拆分");
				purchaseStorageNew.setStoOrderNo("G" + DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)
						+ "U" + String.format("%0" + 4 + "d", purchaseStorage.getBuyerId())
						+ sequenceUtilService.gainPOSequence());
				purchaseStorageService.insert(purchaseStorageNew);
				for (PurchaseStorageDetail purchaseStorageDetail : spiltNewDetail) {
					purchaseStorageDetail.setStorageId(purchaseStorageNew.getId());
					purchaseStorageDetail.setCompanyId(purchaseStorageNew.getCompanyId());// 采购入库明细
					purchaseStorageDetail.setGmtCreate(new Date());
					purchaseStorageDetail.setGmtModify(new Date());
					purchaseStorageDetail.setStoOrderNo(purchaseStorageNew.getStoOrderNo());
					purchaseStorageDetail.setWarehouseId(purchaseStorageNew.getWarehouseId());
					purchaseStorageDetail.setWarehouseName(purchaseStorageNew.getWarehouseName());
					purchaseStorageDetail.setOnlineNumber(purchaseStorageNew.getOnlineNumber());
				}

				purchaseStorage.setOnlineNumber(null);
				purchaseStorageDetailMapper.insertBatch(spiltNewDetail);
			}
		} 
		return spiltOldDetail;
	}
    
}
